package com.ladybug.flow.common.resolvers;

import com.ladybug.flow.common.security.dto.LoginUserDTO;
import com.ladybug.flow.common.annotation.LoginUser;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
* @description: 登录用户解析器
* @author long
* @date 2022/10/17 16:46
* @version 1.0
*/
public class LoginUserResolver implements HandlerMethodArgumentResolver {

    /*
     * @Author long
     * @Description 判断是否为注解类
     * @Date 16:46 2022/10/17
     * @Param [methodParameter]
     * @return boolean 
     **/
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(LoginUser.class);
    }

    /*
     * @Author long
     * @Description //处理@LoginUser
     * @Date 16:47 2022/10/17
     * @Param [methodParameter, modelAndViewContainer, nativeWebRequest, webDataBinderFactory]
     * @return java.lang.Object
     **/
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUserDTO loginUserDTO = (LoginUserDTO) authentication.getPrincipal();
        return loginUserDTO;
    }
}
